import {
  MeshBasicMaterial,
  Sprite,
  SpriteMaterial,
  Texture,
  TextureLoader
} from 'three';

// 创建文字
export const makeTextSprite = (text, color, parameters) => {
  if (parameters === undefined) parameters = {};
  let fontface = parameters.hasOwnProperty('fontface')
    ? parameters['fontface']
    : 'Arial';
  let fontsize = parameters.hasOwnProperty('fontsize')
    ? parameters['fontsize']
    : 32;
  let borderThickness = parameters.hasOwnProperty('borderThickness')
    ? parameters['borderThickness']
    : 4;
  let borderColor = parameters.hasOwnProperty('borderColor')
    ? parameters['borderColor']
    : { r: 0, g: 0, b: 0, a: 1.0 };
  let canvas = document.createElement('canvas');
  let context = canvas.getContext('2d');
  context.font = fontsize + 'px ' + fontface;
  let metrics = context.measureText(text);
  let textWidth = metrics.width;
  context.strokeStyle =
    'rgba(' +
    borderColor.r +
    ',' +
    borderColor.g +
    ',' +
    borderColor.b +
    ',' +
    borderColor.a +
    ')';
  context.lineWidth = borderThickness;
  context.fillStyle = color ? color : '#ffffff';
  context.fillText(text, borderThickness, fontsize + borderThickness);
  context.font = 48 + 'px ' + fontface;
  context.width = textWidth;
  let texture = new Texture(canvas);
  texture.needsUpdate = true;
  let spriteMaterial = new SpriteMaterial({ map: texture });
  return new Sprite(spriteMaterial);
};

// 创建圆形文字
export const makeCycleTextSprite = (
  text,
  color = 'black',
  borderColor = 'white',
  textColor = 'white',
  W = 100,
  H = 100,
  borderWidth = 6
) => {
  let canvas = document.createElement('canvas');
  canvas.width = W;
  canvas.height = H;
  let ctx = canvas.getContext('2d');
  ctx.beginPath();
  ctx.arc(
    (W + borderWidth) / 2,
    (H + borderWidth) / 2,
    40,
    0,
    Math.PI * 2,
    true
  );
  ctx.closePath();
  // 填充背景颜色
  ctx.fillStyle = color;
  ctx.fill();
  // 填充边框颜色
  ctx.lineWidth = borderWidth;
  ctx.lineCap = 'round';
  ctx.strokeStyle = borderColor;
  ctx.stroke();
  // 填充文字颜色
  ctx.font = '64px Arial';
  ctx.fillStyle = textColor;
  ctx.textAlign = 'center';
  let metrics = ctx.measureText(text);
  ctx.fillText(
    text,
    (W + borderWidth) / 2,
    (H + borderWidth * 2) / 2 +
      metrics.fontBoundingBoxDescent +
      metrics.actualBoundingBoxDescent * 4
  );
  let texture = new Texture(canvas);
  texture.needsUpdate = true;
  let spriteMaterial = new SpriteMaterial({
    map: texture,
    transparent: true,
    opacity: 0.8
  });
  let sprite = new Sprite(spriteMaterial);
  return sprite;
};

export const basicMesh = collect => {
  collect.BlackBasicMaterial = new MeshBasicMaterial({ color: 'black' });
  collect.TextureLoader = new TextureLoader();
};
